package com.qdxht.dispenser.ui.activity.main;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.Toast;
import android.app.AlertDialog;
import android.os.Process;
import android.widget.ScrollView;

import com.qdxht.dispenser.base.BaseActivity;
import com.qdxht.dispenser.databinding.ActivityParamSettingsBinding;
import com.qdxht.dispenser.ui.models.entity.ConfigEntity;
import com.qdxht.dispenser.utils.ConfigUtil;
import com.qdxht.dispenser.base.manager.ActivityManager;

public class ParamSettingsActivity extends BaseActivity<ActivityParamSettingsBinding> {

    public static void start(Context context) {
        Intent intent = new Intent(context, ParamSettingsActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected ActivityParamSettingsBinding getBinding() {
        return ActivityParamSettingsBinding.inflate(getLayoutInflater());
    }

    @Override
    protected void initView() {
        ConfigEntity config = ConfigUtil.getConfig();
        if (config != null) {
            binding.etMqttIp.setText(config.getMqttIp());
            binding.etMqttPort.setText(String.valueOf(config.getMqttPort()));
            binding.etMqttUserName.setText(config.getMqttUserName());
            binding.etMqttPassword.setText(config.getMqttPassword());
        }
        binding.btnSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                saveConfig();
            }
        });
        
        // 为所有输入框设置焦点监听，确保键盘弹出时滚动到当前输入框
        setupFocusChangeListeners();
        
        // 设置软键盘模式，确保布局能够适应键盘
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
    }
    
    /**
     * 为所有输入框设置焦点变化监听
     */
    private void setupFocusChangeListeners() {
        View.OnFocusChangeListener focusChangeListener = (v, hasFocus) -> {
            if (hasFocus) {
                // 短暂延迟，确保键盘完全弹出后再滚动
                v.postDelayed(() -> {
                    // 获取当前输入框在父容器中的位置
                    int[] location = new int[2];
                    v.getLocationInWindow(location);
                    
                    // 获取屏幕高度
                    int screenHeight = getResources().getDisplayMetrics().heightPixels;
                    
                    // 获取键盘高度（估算为屏幕高度的40%）
                    int keyboardHeight = screenHeight / 5 * 2;
                    
                    // 计算输入框底部位置
                    int editTextBottom = location[1] + v.getHeight();
                    
                    // 计算需要滚动的距离，确保输入框在键盘上方可见
                    // 如果输入框底部位置超过了(屏幕高度-键盘高度)，则需要向上滚动
                    int visibleThreshold = screenHeight - keyboardHeight;
                    
                    if (editTextBottom > visibleThreshold) {
                        // 需要滚动的距离
                        int scrollY = editTextBottom - visibleThreshold + 50; // 额外50px的缓冲空间
                        
                        // 获取ScrollView并滚动
                        ScrollView scrollView = (ScrollView) binding.getRoot().getChildAt(1);
                        int currentScrollY = scrollView.getScrollY();
                        scrollView.smoothScrollBy(0, scrollY);
                    }
                }, 300);
            }
        };
        
        // 为每个输入框设置焦点监听器
        binding.etMqttIp.setOnFocusChangeListener(focusChangeListener);
        binding.etMqttPort.setOnFocusChangeListener(focusChangeListener);
        binding.etMqttUserName.setOnFocusChangeListener(focusChangeListener);
        binding.etMqttPassword.setOnFocusChangeListener(focusChangeListener);
    }

    @Override
    protected void initData() {
        // 无需实现
    }

    private void saveConfig() {
        ConfigEntity entity = ConfigUtil.getConfig();
        if (entity == null) {
            entity = new ConfigEntity();
        }
        entity.setMqttIp(binding.etMqttIp.getText().toString().trim());
        entity.setMqttPort(parseInt(binding.etMqttPort.getText().toString().trim(), 1883));
        entity.setMqttUserName(binding.etMqttUserName.getText().toString().trim());
        entity.setMqttPassword(binding.etMqttPassword.getText().toString().trim());
        ConfigUtil.saveConfig(entity);
        new AlertDialog.Builder(this)
            .setTitle("提示")
            .setMessage("修改系统配置，需要重启应用！")
            .setCancelable(false)
            .setPositiveButton("确定", (dialog, which) -> {
                Process.killProcess(Process.myPid());
                Intent intent = getBaseContext().getPackageManager()
                        .getLaunchIntentForPackage(getBaseContext().getPackageName());
                if (intent != null) {
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(intent);
                }
            })
            .show();
    }

    private int parseInt(String str, int def) {
        try {
            return Integer.parseInt(str);
        } catch (Exception e) {
            return def;
        }
    }

} 